//
//  TakePhotoController.m
//  3DModelCollector
//
//  Created by Jing Zhang on 7/19/12.
//  Copyright (c) 2012 Tencent. All rights reserved.
//

#import "TakePhotoController.h"
#import "PhotoReviewController.h"
#import "SelectPhotoController.h"
#import "BasicStructure.h"
#import <QuartzCore/QuartzCore.h>

@interface TakePhotoController ()

@property (retain, nonatomic) IBOutlet UILabel *locationIndicator;
@property (retain, nonatomic) IBOutlet UILabel *headingIndicator;
@property (retain, nonatomic) IBOutlet UIButton *takePhotoButton;
@property (retain, nonatomic) IBOutlet UIButton *switchButton;
@property (retain, nonatomic) IBOutlet UIView *purposeSelectView;


@property (nonatomic, retain) UIImagePickerController* picker;
@property (nonatomic) BOOL isTipViewExpanded;
@property (nonatomic, retain) NSArray* purposeSet;

@property (nonatomic, retain) CLLocationManager* locationManager;
@property (nonatomic) CLLocationCoordinate2D coordinate;
@property (nonatomic) double heading;

- (IBAction)onClickTakePhoto:(id)sender;
- (IBAction)onClickSelectExist:(id)sender;
- (IBAction)onClickCancel:(id)sender;
- (IBAction)onClickSelectPurpose:(id)sender;
- (IBAction)onSwitchTipView:(id)sender;
- (IBAction)onClosePurposeView:(id)sender;

- (void)popUpPurposeView:(BOOL)animated;
- (void)closePurposeView:(BOOL)animated;
- (void)expandTipView:(BOOL)animated;
- (void)shrinkTipView:(BOOL)animated;

@end

@implementation TakePhotoController

@synthesize photoInfo = _photoInfo;
@synthesize photoInfoList = _photoInfoList;
@synthesize photoDelegate = _photoDelegate;

@synthesize locationIndicator = _locationIndicator;
@synthesize headingIndicator = _headingIndicator;
@synthesize takePhotoButton = _takePhotoButton;
@synthesize switchButton = _switchButton;
@synthesize purposeSelectView = _purposeSelectView;
@synthesize picker = _picker;
@synthesize isTipViewExpanded = _isTipViewExpanded;
@synthesize purposeSet = _purposeSet;

@synthesize locationManager = _locationManager;
@synthesize coordinate = _coordinate;
@synthesize heading = _heading;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.wantsFullScreenLayout = YES;
        self.isTipViewExpanded = YES;
        
        self.purposeSet = [NSArray arrayWithObjects:@"计算楼层", @"上层纹理", @"大门", @"上层广告牌", @"底商商铺", nil];
    }
    
    return self;
}

- (void)dealloc {
    self.purposeSet = nil;
    self.picker = nil;
    self.locationManager = nil;
    
    self.photoInfo = nil;
    self.photoInfoList = nil;
    self.photoDelegate = nil;
    
    [_locationIndicator release];
    
    [_takePhotoButton release];
    [_switchButton release];
    [_headingIndicator release];
    [_purposeSelectView release];

    [super dealloc];
}

- (void)loadView {
    
    [super loadView];
    
    [self shrinkTipView:NO];
    
    UIView* visibleView = [self.purposeSelectView viewWithTag:10];
    visibleView.layer.masksToBounds = YES;
    visibleView.layer.cornerRadius = 20;
    
    [self closePurposeView:NO];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    UIImagePickerController* picker = [[UIImagePickerController alloc] init];
    picker.sourceType = UIImagePickerControllerSourceTypeCamera;
    picker.delegate = self;
    picker.showsCameraControls = NO;
    picker.editing = NO;
    picker.view.frame = CGRectMake(0, 0, 320, 436);
    self.picker = picker;
    [picker release];
    
    [self.view addSubview:picker.view];
    [self.view sendSubviewToBack:picker.view];
    
    // 开始定位
    CLLocationManager* locationMgr = [[CLLocationManager alloc] init];
    self.locationManager = locationMgr;
    [locationMgr release];
    
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 5.0f;
    self.locationManager.headingFilter = 1.0f;
    
    self.locationIndicator.text = @"正在定位位置";
    self.headingIndicator.text = @"正在定位朝向";
    self.takePhotoButton.enabled = NO;
    
    [self popUpPurposeView:YES];
}

- (void)viewDidUnload
{
    [self setLocationIndicator:nil];
    [self setTakePhotoButton:nil];
    [self setSwitchButton:nil];
    [self setHeadingIndicator:nil];
    [self setPurposeSelectView:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
    self.picker = nil;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];
    
    if (self.locationManager != nil) {
        [self.locationManager startUpdatingLocation];
        [self.locationManager startUpdatingHeading];
    }
    
    [[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationFade ];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    if (self.locationManager != nil) {
        [self.locationManager stopUpdatingLocation];
        [self.locationManager stopUpdatingHeading];
    }
    
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - [UITableViewDataSource] 

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.purposeSet.count;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    static NSString* cellID = @"CellID";
    UITableViewCell* cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    
    NSString* str = [self.purposeSet objectAtIndex:indexPath.row];
    cell.textLabel.text = str;

    int v = 1 << indexPath.row;
    if (self.photoInfo.purposeFlag & v) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
   
    return cell;
}

#pragma mark - [UITableViewDelegate]

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    UITableViewCell* cell = [tableView cellForRowAtIndexPath:indexPath];
    int flag = (1 << indexPath.row);
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
        self.photoInfo.purposeFlag |= flag;
    }
    else {
        cell.accessoryType = UITableViewCellAccessoryNone;
        self.photoInfo.purposeFlag &= ~flag;
    }
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - [UIImagePickerControllerDelegate]

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    UIImage* photo = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    PhotoReviewController* photoReviewController = [[PhotoReviewController alloc] initWithNibName:@"PhotoReviewController" bundle:nil];
    photoReviewController.photo = photo;
    self.photoInfo.coordinate = self.coordinate;
    self.photoInfo.direction = self.heading;
    photoReviewController.photoInfo = self.photoInfo;
    photoReviewController.photoDelegate = self.photoDelegate;
    [self.navigationController pushViewController:photoReviewController animated:YES];
    [photoReviewController release];
}

#pragma mark - [CLLocationManagerDelegate]

- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
    
    NSLog(@"Location : %f, %f", newLocation.coordinate.longitude, newLocation.coordinate.latitude);
    self.coordinate = newLocation.coordinate;

    self.locationIndicator.text = [NSString stringWithFormat:@"%f, %f", newLocation.coordinate.longitude, newLocation.coordinate.latitude];
    self.takePhotoButton.enabled = YES;
}

- (void)locationManager:(CLLocationManager *)manager didUpdateHeading:(CLHeading *)newHeading {
    
    NSLog(@"Heading : %f", newHeading.trueHeading);
    self.heading = newHeading.trueHeading;
    self.headingIndicator.text = [NSString stringWithFormat:@"偏北%2f度", newHeading.trueHeading];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:@"暂时无法定位" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
    [alertView show];
    [alertView release];
}

#pragma mark - [Private methods]

- (IBAction)onClickTakePhoto:(id)sender {
    
    if (self.picker != nil) {
        [self.picker takePicture];
    }
}

- (IBAction)onClickSelectExist:(id)sender {
    
    SelectPhotoController* selectController = [[SelectPhotoController alloc] initWithNibName:@"SelectPhotoController" bundle:nil];
    selectController.photoInfoList = self.photoInfoList;
    [self.navigationController pushViewController:selectController animated:YES];
    [selectController release];
}

- (IBAction)onClickCancel:(id)sender {
    
    [self.navigationController dismissModalViewControllerAnimated:YES];
}

- (IBAction)onClickSelectPurpose:(id)sender {
    
    [self popUpPurposeView:YES];
}

- (IBAction)onSwitchTipView:(id)sender {
    
    if (self.isTipViewExpanded) {
        [self shrinkTipView:YES];
    }
    else {
        [self expandTipView:YES];
    }
}

- (IBAction)onClosePurposeView:(id)sender {
    
    [self closePurposeView:YES];
}

- (void)popUpPurposeView:(BOOL)animated {
    
    UIView* contentView = [self.purposeSelectView viewWithTag:10];
    if (animated) {
        self.purposeSelectView.hidden = NO;
        [UIView animateWithDuration:0.4f 
                         animations:^() {
                             
                             contentView.frame = CGRectMake(60, 77, 200, 323);
                         }
                         completion:^(BOOL finished) {
                             
                         }];
    }
    else {
        self.purposeSelectView.hidden = NO;
        contentView.frame = CGRectMake(60, 77, 200, 323);
    }
}

- (void)closePurposeView:(BOOL)animated {
    
    UIView* contentView = [self.purposeSelectView viewWithTag:10];
    CGRect targetFrame = CGRectMake(264, 60, 1, 1);
    if (animated) {
      
        [UIView animateWithDuration:0.4f 
                         animations:^() {
                             contentView.frame = targetFrame;
                         }
                         completion:^(BOOL finished) {
                             self.purposeSelectView.hidden = YES;
                         }];
    }
    else {
        contentView.frame = targetFrame;
        self.purposeSelectView.hidden = YES;
    }
}

- (void)expandTipView:(BOOL)animated {
    
    if (self.isTipViewExpanded) {
        return;
    }
    
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4f];
    }
    
    UIView* view = [self.view viewWithTag:10];
    CGRect frame = view.frame;
    frame.origin.y = 426 - frame.size.height;
    view.frame = frame;
    
    frame = self.switchButton.frame;
    frame.origin.y = 426 - view.frame.size.height - frame.size.height;
    self.switchButton.frame = frame;

    if (animated) {
        [UIView commitAnimations];
    }
    
    self.isTipViewExpanded = !self.isTipViewExpanded;
}

- (void)shrinkTipView:(BOOL)animated {
    
    if (!self.isTipViewExpanded) {
        return;
    }
    
    if (animated) {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4f];
    }
    
    UIView* view = [self.view viewWithTag:10];
    CGRect frame = view.frame;
    frame.origin.y = 426;
    view.frame = frame;
    
    frame = self.switchButton.frame;
    frame.origin.y = 426 - frame.size.height;
    self.switchButton.frame = frame;
    
    if (animated) {
        [UIView commitAnimations];
    }
    
    self.isTipViewExpanded = !self.isTipViewExpanded;
}

@end
